package com.white.mysoundrecorder;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by yutf on 2017/8/30 0030.
 */

public class FileListFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener
{

    RecyclerView recyclerView;
    NewSwipeRefresh swipe;
    Adapter adapter;
    TextView tvNodata;
    private List<RecordItem> datas;
    private Player player;

    public static FileListFragment getInstance()
    {
        return new FileListFragment();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser)
    {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser && isViewCreated)
        {
            swipe.setRefreshing(true);
        }
        player = Player.getInstance();
    }

    private boolean isViewCreated;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        View v = inflater.inflate(R.layout.frag_list, null);
        findViews(v);
        isViewCreated = true;
        datas = new ArrayList<>();
        swipe.setRefreshing(true);
        return v;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);
    }

    private void findViews(View v)
    {
        recyclerView = (RecyclerView) v.findViewById(R.id.cycle);
        tvNodata = (TextView) v.findViewById(R.id.tv_nodata);
        swipe = (NewSwipeRefresh) v.findViewById(R.id.swipe);
        swipe.setOnRefreshListener(this);
    }

    @Override
    public void onRefresh()
    {
        new RecordListTask(getContext()).execute();
    }

    private class RecordListTask extends AsyncTask<Void, List<RecordItem>, List<RecordItem>>
    {
        ProgressDialog dialog;
        Context mContext;

        public RecordListTask(Context ctx)
        {
            mContext = ctx;
        }

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            dialog = new ProgressDialog(getContext());
            dialog.setMessage("加载中...");
            dialog.show();
        }

        @Override
        protected List<RecordItem> doInBackground(Void... params)
        {
            MyDbHelper m = new MyDbHelper(getContext());
            return m.getAll();
        }

        private int newCount;

        @Override
        protected void onPostExecute(List<RecordItem> recordItems)
        {
            dialog.dismiss();
            swipe.setRefreshing(false);
            if(recordItems != null && recordItems.size() > 0)
            {
                newCount = recordItems.size();
                tvNodata.setVisibility(View.GONE);
                datas.clear();
                datas.addAll(0, recordItems);
                configAdapter();
            }else
            {
                tvNodata.setVisibility(View.VISIBLE);
            }
            super.onPostExecute(recordItems);
        }

        private void configAdapter()
        {
            if(adapter == null)
            {
                adapter = new Adapter();
                LinearLayoutManager m = new LinearLayoutManager(mContext, OrientationHelper.VERTICAL, false);
                recyclerView.setLayoutManager(m);
                recyclerView.setAdapter(adapter);
            }
            adapter.notifyDataSetChanged();
        }
    }

    private class Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
    {
        SimpleDateFormat sdf1 = new SimpleDateFormat("mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
        {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_record, null);
            return new VH(v);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            RecordItem r = datas.get(position);

            VH ho = (VH) holder;

            ho.title.setText(r.name);
            ho.play.setTag(position);
            ho.position = position;
            ho.time.setText(sdf1.format(new Date(r.duration)));
            ho.addTime.setText(sdf2.format(new Date(r.addTime)));
            bindEvent(ho, position);
        }

        private void bindEvent(final VH holder, int position)
        {
            holder.play.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    int pos = (Integer) v.getTag();
                    RecordItem i = datas.get(pos);
                    switch(i.playState)
                    {
                        case Player.st_default:
                            player.start(i, pos);
                            break;
                        case Player.st_playing:
                            player.pause();
                            break;
                        case Player.st_pause:
                            player.start(i, pos);
                            break;
                        case Player.st_preparing:
                            break;
                    }
                }
            });
            player.setPlayListener(new Player.PlayListener()
            {
                @Override
                public void onComplete()
                {
                    holder.play.setImageResource(R.drawable.play);
                    notifyItemChanged(holder.position);
                }

                @Override
                public void onStart(int s)
                {
                    holder.time.setText(sdf1.format(new Date(s)));
                    holder.pb.setMax(s);
                    holder.play.setImageResource(R.drawable.pause);
                }

                @Override
                public void onPause()
                {
                    holder.play.setImageResource(R.drawable.play);
                }

                @Override
                public void onStop(RecordItem item, int pos)
                {
                    holder.play.setImageResource(R.drawable.play);
                    notifyItemChanged(pos);
                }

                @Override
                public void onResume()
                {
                    holder.play.setImageResource(R.drawable.pause);
                }

                @Override
                public void onProgress(int p, int position)
                {
                    holder.pb.setProgress(p);
                }
            });
        }

        @Override
        public int getItemCount()
        {
            return datas == null ? 0 : datas.size();
        }

        private class VH extends RecyclerView.ViewHolder
        {
            CardView card;
            TextView title;
            ImageButton play, more;
            ProgressBar pb;
            TextView time, addTime;
            int position;

            public VH(View v)
            {
                super(v);
                findItemViews(v);
            }

            private void findItemViews(View v)
            {
                card = (CardView) v.findViewById(R.id.card);
                title = (TextView) v.findViewById(R.id.title);
                play = (ImageButton)v.findViewById(R.id.play);
                pb = (ProgressBar) v.findViewById(R.id.progress);
                time = (TextView) v.findViewById(R.id.duration);
                more = (ImageButton) v.findViewById(R.id.more);
                addTime = (TextView) v.findViewById(R.id.add_time);
            }
        }
    }
}
